<template>
  <Card>
    <p slot="title">
      <span style="color:red;fontWeight:normal">角色管理</span>
    </p>
    <div style='width: 100%; height: 100%'>
      <div class="feature-btn">
        <Button type="primary" icon="plus" @click="addRole('formValidate')" :disabled="!this.ACTIONS['role.add']">添加</Button>
        <div class="searchAndBtn">
          <Input class="search-input" placeholder="请输入角色名关键字" v-model="searchData"></Input>
          <Button type="primary" icon="ios-search" @click="searchClick(searchData)" :disabled="!this.ACTIONS['role.search']" style='float: right'>搜索</Button>
        </div>
      </div>
      <div class="table-relative">
        <div class="table-body commonCss">
          <!-- :height="defaultHeight" -->
          <Table border size="small" :columns="columns7" :data="data6" :no-data-text="noData"></Table>
        </div>
      </div>
      <div class="page-style">
        <Page :total="roleCounts" :current="taskQueryPage" :page-size="pageLimit" @on-change="pageChange" @on-page-size-change='pageSize' show-sizer placement='top' :page-size-opts='pageLimitOpts'></Page>
      </div>
      <Modal class='commonCss' v-model="model1" @on-cancel='cancelBaseData' :mask-closable="false" title="角色">
        <Form ref='formValidate' :model='post' :rules="rulePost">
          <FormItem label='角色名' prop="name">
            <p>
              <Input type='text' v-model.trim="post.name" placeholder='请输入姓名...' class='disStyle part' :disabled='sureDisabled'></Input>
            </p>
          </FormItem>
          <FormItem label='角色描述' prop='desc'>
            <p>
              <Input type='textarea' v-model="post.desc" placeholder="角色描述..." class='disStyle'></Input>
            </p>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button @click="cancelBaseData" style='background:none; border:none'>取消</Button>
          <Button type='primary' @click="modSure(post)">确定</Button>
        </div>
      </Modal>
      <Modal class='commonCss' v-model="model2" style='overflow-y: auto;' @on-ok="dataPowerSure()" :mask-closable="false" @on-cancel='cancelSetPower' title="数据权限">
        <Datas :orgTree='orgTree' @data-power='getSetDataPower'></Datas>
      </Modal>
      <Modal class='commonCss' v-model="model3" style='overflow-y: auto;' @on-ok="funPowerSure()" :mask-closable="false" @on-cancel='cancelSetPower' title="功能权限">
        <Funs :funcTree='funcTree' @function-power='getSetFunPower'></Funs>
      </Modal>
    </div>
  </Card>
</template>
<script>
// import './common.less'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import Funs from './funPower'
import Datas from './dataPower'
export default {
  components: {
    Funs,
    Datas
  },
  props: {
  },
  data() {
    const nameCheck = (role, value, callback) => {
      const postRoleName = encodeURIComponent(this.post.name).trim()
      const chenkValue = /^[0-9a-zA-Z-_—\u4e00-\u9fa5]{0,32}$/
      if (postRoleName === '') {
        callback(new Error('角色名不能为空'))
      } else if (!chenkValue.test(value)) {
        callback(new Error('请输入汉字、数字、字母、-、——、_，并且长度不能超过32！'))
      } else {
        this.checkRoleName(postRoleName).then((resp) => {
          resp.data ? callback(new Error('角色名已存在,请重新输入')) : callback()
        }).catch((err) => {
          const checkRoleName = '角色名唯一性验证失败'
          this.showInfo(err, checkRoleName)
          console.log('this.checkRoleName:' + err)
        })
      }
    }
    return {
      roleCounts: 20,
      columns7: [
        {
          type: 'index',
          title: '序号',
          width: 100,
          align: 'center'
        },
        {
          title: '姓名',
          key: 'name',
          width: 200,
          align: 'center',
          className: 'demo-table-info-column',
          render: (h, params) => {
            return h('div', [
              h('Icon', {
                props: {
                  type: 'person'
                }
              }),
              h('strong', params.row.name)
            ])
          }
        },
        {
          title: '描述',
          align: 'center',
          key: 'desc'
        },
        {
          title: '操作',
          key: 'action',
          width: 300,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  disabled: !this.ACTIONS['role.mod']
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.modBtn(params.row, params.index)
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  disabled: !this.ACTIONS['role.dataPower']
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.setRoleDataPower(params.row)
                  }
                }
              }, '数据权限'),
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  disabled: !this.ACTIONS['role.funPower']
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.setRoleFunPower(params.row)
                  }
                }
              }, '功能权限'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small',
                  disabled: !this.ACTIONS['role.del']
                },
                on: {
                  click: () => {
                    this.remove(params.row.id)
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      searchData: '',
      taskQueryPage: 1,
      taskQueryLimit: this.$store.getters.pageLimit,
      defaultHeight: 432,
      noData: '暂无角色，请添加。',
      data6: [],
      model1: false,
      model2: false,
      model3: false,
      sureDisabled: false,
      post: {
        id: '',
        name: '',
        desc: ''
      },
      savePost: {},
      rulePost: {
        name: [
          { required: true, validator: nameCheck, trigger: 'blur' },
          { required: true, validator: nameCheck, trigger: 'change' }]
      },
      dataPower: {
        roleId: '',
        orgIds: []
      },
      funPower: {
        roleId: '',
        actionIds: []
      },
      mod: false,
      treeData: {},
      orgTree: [],
      funcTree: []
    }
  },
  computed: {
    ...mapState({
      // roleData: ({ rolePower }) => rolePower.roleData,
      // powerDatas: ({ rolePower }) => rolePower.powerDatas,
      // roleCounts: ({ rolePower }) => rolePower.rolePage.counts,
      // emptyData: ({ rolePower }) => rolePower.emptyDataPower,
      // emptyFun: ({ rolePower }) => rolePower.emptyFunPower
    }),
    ...mapGetters(['ACTIONS', 'pageLimitOpts', 'pageLimit'])
  },
  created() {
    this.savePost = this.$lodash.cloneDeep(this.post)
    this.getRoles()
  },
  methods: {
    ...mapMutations(['SET_TREE_SHOW']),
    ...mapActions(['getRoleDatas', 'getSearchRole', 'addOneRole', 'modOneRole', 'delOneRole', 'funcTreeData', 'orgsTreeData', 'setPowerToRole', 'getPowerToRole', 'checkRoleName']),
    modBtn(row, index) {
      this.$refs.formValidate.resetFields()
      this.mod = true
      this.post.id = row.id
      this.post.name = row.name
      this.post.desc = row.desc
      this.sureDisabled = this.model1 = true
    },
    remove(id) {
      this.$Modal.confirm({
        content: '<p>确定删除该角色?</p>',
        onOk: () => {
          // this.delOneRole(id).then((resp) => {
          //   if (resp.code === 2101) {
          //     this.$Notice.error({
          //       title: '警告',
          //       desc: '该角色已被使用，无法删除！',
          //       duration: 3
          //     })
          //   }
          //   this.$Message.success('删除角色成功')
          //   this.getRoles()
          // }).catch((err) => {
          //   const delRole = '删除角色失败！'
          //   this.showInfo(err, delRole)
          //   console.log('this.delOneRole:' + err)
          // })
        }
      })
    },
    getRoles() {
      // this.getRoleDatas({
      //   limit: this.taskQueryLimit,
      //   page: this.taskQueryPage
      // }).then((resp) => {
      //   this.data6 = this.roleData
      // }).catch((err) => {
      //   const rolesList = '获取角色列表失败！'
      //   this.showInfo(err, rolesList)
      //   console.log('this.getRoleDatas' + err)
      // })
    },
    showInfo(err, info) {
      if (err.response.status === 403) {
        this.$Notice.error({
          title: '警告',
          desc: '没有设置相关权限！',
          duration: 3
        })
      } else {
        this.$Notice.error({
          title: '警告',
          desc: info,
          duration: 3
        })
      }
    },
    getSetFunPower(power) {
      this.funPower.actionIds = power
    },
    getSetDataPower(power) {
      this.dataPower.orgIds = power
    },
    dataToTree(arr, power) {
      arr.forEach((item) => {
        setPower(item, power)
        if (item.name) {
          item.title = item.name
        }
        if (item.children && item.children.length) {
          this.dataToTree(item.children, power)
        }
      })
      function setPower(item, arr) {
        if (arr === undefined) return
        if (arr.length) {
          arr.forEach((id) => {
            if (id === item.id && !item.children) {
              item.checked = true
            }
          })
        }
        return item
      }
      return arr
    },
    pageChange(page) {
      this.taskQueryPage = page
      this.getRoles()
    },
    pageSize(num) {
      this.taskQueryLimit = num
      this.getRoles()
    },
    searchClick(data) {
      // this.getSearchRole(encodeURIComponent(data)).then(resp => {
      //   this.data6 = this.roleData
      // }).catch((err) => {
      //   const searchRole = '搜索角色失败！'
      //   this.showInfo(err, searchRole)
      //   console.log('this.searchClick:' + err)
      // })
    },
    addRole(name) {
      this.$refs[name].resetFields()
      this.model1 = true
      this.post.name = ''
      this.post.desc = ''
      this.post.id = ''
      this.sureDisabled = false
    },
    cancelBaseData() {
      this.post = this.savePost
      this.sureDisabled = this.mod = this.model1 = false
    },
    modSure(data) {
      // if (this.mod) {
      //   this.modOneRole(data).then(() => {
      //     this.$Message.success('修改角色成功')
      //     this.getRoles()
      //     this.mod = false
      //     this.sureDisabled = false
      //   }).catch((err) => {
      //     const modeRole = '修改角色失败！'
      //     this.showInfo(err, modeRole)
      //     console.log('this.modOneRole' + err)
      //   })
      // } else {
      //   this.$refs.formValidate.validate((valid) => {
      //     if (valid) {
      //       this.addOneRole(data).then((resp) => {
      //         this.$Message.success('添加角色成功')
      //         this.getRoles()
      //       }).catch((err) => {
      //         const newRole = '添加角色失败！'
      //         this.showInfo(err, newRole)
      //         console.log('this.addOneRole:' + err)
      //       })
      //     } else {
      //       this.model1 = true
      //       this.$Notice.error({
      //         title: '警告',
      //         desc: '请填写正确的信息！',
      //         duration: 3
      //       })
      //     }
      //   })
      // }
    },
    setRoleDataPower(row) {
      // this.$store.commit('SET_TREE_SHOW', true)
      // this.dataPower.roleId = row.id
      // this.getPowerToRole(row.id).then((resp) => {
      //   this.treeData = JSON.parse(JSON.stringify(this.powerDatas))
      //   this.orgTree = this.dataToTree(this.treeData.orgTree.data, this.treeData.orgIds)
      //   this.model2 = true
      // }).catch((err) => {
      //   const newDataPower = '设置角色数据权限失败！'
      //   this.showInfo(err, newDataPower)
      //   console.log('this.getPowerToRole:' + err)
      // })
    },
    setRoleFunPower(row) {
      // this.$store.commit('SET_TREE_SHOW', true)
      // this.funPower.roleId = row.id
      // this.getPowerToRole(row.id).then((resp) => {
      //   this.treeData = JSON.parse(JSON.stringify(this.powerDatas))
      //   this.funcTree = this.dataToTree(this.treeData.actionTree, this.treeData.actionIds)
      //   this.model3 = true
      // }).catch((err) => {
      //   const newFuncPower = '设置角色功能权限失败！'
      //   this.showInfo(err, newFuncPower)
      //   console.log('this.getPowerToRole:' + err)
      // })
    },
    dataPowerSure() {
      // this.emptyData ? this.dataPower = this.dataPower : this.dataPower.orgIds = this.treeData.orgIds
      // this.orgsTreeData(this.dataPower).then((resp) => {
      //   this.orgTree = []
      // }).catch((err) => {
      //   const getRoleDatas = '设置角色数据权限失败！'
      //   this.showInfo(err, getRoleDatas)
      //   console.log('this.orgsTreeData:' + err)
      // })
    },
    funPowerSure() {
      // this.emptyFun ? this.funPower = this.funPower : this.funPower.actionIds = this.treeData.actionIds
      // this.funcTreeData(this.funPower).then((resp) => {
      //   this.funcTree = []
      // }).catch((err) => {
      //   const getRoleFunc = '设置角色功能权限失败！'
      //   this.showInfo(err, getRoleFunc)
      //   console.log('this.funcTreeData:' + err)
      // })
    },
    cancelSetPower() {
      this.orgTree = []
      this.funcTree = []
      this.model2 = this.model3 = false
    }
  }
}
</script>
<style lang='less' scoped>
.feature-btn {
  width: 93%;
  height: 35px;
  line-height: 35px;
  margin: 10px auto;
  padding: 0;
}

.feature-btn>button {
  margin: 0 15px 0 0px;
  float: left;
}

.searchAndBtn {
  width: 370px;
  float: right;
  .search-input {
    width: 250px;
    float: left;
    margin-left: 30px;
  }
}

.disStyle {
  margin-left: 8px;
}

.disStyle.part {
  margin-left: 10px;
}

.table-relative {
  width: 93%;
  height: 90%;
  margin: 15px auto;
}

.table-body {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.page-style {
  text-align: right;
  padding-right: 48px;
  height: 45px;
  overflow: hidden;
  margin: 20px 0px;
}
</style>
